package com.topscore.uke.ui.activities;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.topscore.uke.R;
import com.topscore.uke.entities.AddressListItem;
import com.topscore.uke.entities.MemberMobPosInfo;
import com.topscore.uke.mvp.contractors.GetMemberDetailInfoContractor;
import com.topscore.uke.mvp.contractors.GetMemberMobPosInfoContractor;
import com.topscore.uke.mvp.contractors.SaveMemberAddressContractor;
import com.topscore.uke.mvp.presenters.GetMemberBasicInfoPresenter;
import com.topscore.uke.mvp.presenters.GetMemberMPosPresenter;
import com.topscore.uke.mvp.presenters.SaveMemberAddressPresenter;
import com.topscore.uke.network.request.SaveMemberAddressRequest;
import com.topscore.uke.ui.ToolBarCompatActivity;
import com.topscore.uke.ui.loadsir_callback.ErrorCallBack;
import com.topscore.uke.ui.loadsir_callback.LoadingCallBack;
import com.topscore.utillibrary.widget.CircleImageView;
import com.tubb.smrv.SwipeHorizontalMenuLayout;
import com.tubb.smrv.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MemberBasicInfoActivity extends ToolBarCompatActivity implements GetMemberDetailInfoContractor.View {

    CircleImageView avatarIv;
    RelativeLayout tagLayout,consumptionLayout;
    TextView nameTv, mobileTv;
    EditText nameEdt;
    TextView remarkEdt;
    TextView tencentEdt;
    TextView wechatEdt;
    TextView weiboEdt;
    TextView emailEdt;
    TextView mobileEdt;
    TextView birthDayTv, childBirthdayTv;

    SwipeMenuRecyclerView addressRecycler;
    Button createAddressBtn;

    @Bind(R.id.root_recycler)
    RecyclerView rootRecycler;

    private boolean mIsEditing = false;

    private MenuItem mActionEditItem;

    private AddressAdapter mAddressAdapter;

    private String mMemberName, mMemberID, mPhone;

    private MultiItemAdapter mMultiItemAdapter;
    private List<MultiItem> mMultiItemList;

    private final int _Type_Info = 1023, _Type_AddressList = 1024, _Type_AddAddress = 1025;

    private final int _SAVE_MEMBER_ADDRESS_REQUEST_CODE = 1004;

    private GetMemberBasicInfoPresenter mBasicInfoPresenter;

    private LoadService mLoadService;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_edit, menu);
        mActionEditItem = menu.findItem(R.id.action_edit);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_edit:
//                onEditSelected();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        mMemberID = bundle.getString("memberID");
        mMemberName = bundle.getString("memberName");
        mPhone = bundle.getString("phone");
        setContentView(R.layout.activity_member_basic_info);
        ButterKnife.bind(this);
        setCentralTitle("会员基本信息");
        initViews();
    }


    private void onEditSelected() {
        if (mIsEditing) {
            mIsEditing = false;
            mActionEditItem.setTitle("编辑");

            nameEdt.setFocusable(false);
            nameEdt.setFocusableInTouchMode(false);

            remarkEdt.setFocusable(false);
            remarkEdt.setFocusableInTouchMode(false);

            tencentEdt.setFocusable(false);
            tencentEdt.setFocusableInTouchMode(false);

            wechatEdt.setFocusable(false);
            wechatEdt.setFocusableInTouchMode(false);

            weiboEdt.setFocusable(false);
            weiboEdt.setFocusableInTouchMode(false);

            emailEdt.setFocusable(false);
            emailEdt.setFocusableInTouchMode(false);

            mobileEdt.setFocusable(false);
            mobileEdt.setFocusableInTouchMode(false);

        } else {
            mIsEditing = true;
            mActionEditItem.setTitle("完成");

            nameEdt.setFocusable(true);
            nameEdt.setFocusableInTouchMode(true);

            remarkEdt.setFocusable(true);
            remarkEdt.setFocusableInTouchMode(true);

            tencentEdt.setFocusable(true);
            tencentEdt.setFocusableInTouchMode(true);

            wechatEdt.setFocusable(true);
            wechatEdt.setFocusableInTouchMode(true);

            weiboEdt.setFocusable(true);
            weiboEdt.setFocusableInTouchMode(true);

            emailEdt.setFocusable(true);
            emailEdt.setFocusableInTouchMode(true);

            mobileEdt.setFocusable(true);
            mobileEdt.setFocusableInTouchMode(true);
        }
    }

    private void initViews() {
        initAdapters();
        rootRecycler.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rootRecycler.setAdapter(mMultiItemAdapter);
        mLoadService = LoadSir.getDefault().register(rootRecycler, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {

            }
        });
        mBasicInfoPresenter = new GetMemberBasicInfoPresenter(this);
        initData();
    }

    private void initAdapters() {
        mAddressAdapter = new AddressAdapter();
        mMultiItemList = new ArrayList<>();
        mMultiItemList.add(new MultiItem(_Type_Info));
        mMultiItemList.add(new MultiItem(_Type_AddressList));
        mMultiItemList.add(new MultiItem(_Type_AddAddress));
        mMultiItemAdapter = new MultiItemAdapter(mMultiItemList);
    }

    private void initData() {
        mBasicInfoPresenter.getMemberInfo(mMemberID);
    }

    @Override
    public void onLoading(String loadingMessage) {
        mLoadService.showCallback(LoadingCallBack.class);
    }

    @Override
    public void onLoadFinished() {
        mLoadService.showSuccess();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show();
        mLoadService.showCallback(ErrorCallBack.class);
    }


    private class AddressAdapter extends BaseQuickAdapter<AddressListItem, BaseViewHolder> {

        private View emptyView;

        public AddressAdapter() {
            super(R.layout.address_item_layout, new ArrayList<>());
        }

        @Override
        protected void convert(BaseViewHolder holder, AddressListItem item) {
            SwipeHorizontalMenuLayout menuLayout = (SwipeHorizontalMenuLayout) holder.getConvertView();
            holder.setText(R.id.name_tv, item.getReceiverName())
                    .setText(R.id.phone_tv, item.getReceiverContactInfo())
                    .setText(R.id.address_tv, item.getProvince()
                            + item.getCity()
                            + item.getDistrict()
                            + item.getAddress());
            holder.getView(R.id.smMenuViewRight).setOnClickListener(view -> {
                menuLayout.smoothCloseMenu(300);
                new AlertDialog.Builder(mContext)
                        .setMessage("您确定要删除这个地址吗")
                        .setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss())
                        .setPositiveButton("删除", (dialogInterface, i) -> {
                            deleteAddressItem(item);
                            dialogInterface.dismiss();
                        })
                        .create().show();
            });
            holder.getView(R.id.edit_layout).setOnClickListener(view -> {
                SaveMemberAddressRequest addressRequest = new SaveMemberAddressRequest(mPhone);
                addressRequest.setId(item.getId());
                addressRequest.setDistrictId(item.getDistrictId());
                addressRequest.setDistrict(item.getDistrict());
                addressRequest.setCityId(item.getCityId());
                addressRequest.setCity(item.getCity());
                addressRequest.setProvinceId(item.getProvinceId());
                addressRequest.setProvince(item.getProvince());
                addressRequest.setAddress(item.getAddress());
                addressRequest.setReceiverContactInfo(item.getReceiverContactInfo());
                addressRequest.setReceiverName(item.getReceiverName());
                Intent intent = new Intent(mContext, ModifyAddressActivity.class);
                intent.putExtra("address_info", addressRequest);
                intent.putExtra("memberName", mMemberName);
                intent.putExtra("phone", mPhone);
                startActivityForResult(intent, _SAVE_MEMBER_ADDRESS_REQUEST_CODE);
            });
        }
    }

    private void deleteAddressItem(AddressListItem item) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case _SAVE_MEMBER_ADDRESS_REQUEST_CODE:
                if (resultCode == RESULT_OK && data != null) {
//                    SaveMemberAddressRequest saveMemberAddressRequest = data.getParcelableExtra("address_info");
                }
                break;
        }
    }

    private class MultiItem implements MultiItemEntity {

        private int itemType;

        private MultiItem(int itemType) {
            this.itemType = itemType;
        }

        @Override
        public int getItemType() {
            return itemType;
        }

    }

    private class MultiItemAdapter extends BaseMultiItemQuickAdapter<MultiItem, BaseViewHolder> {

        /**
         * Same as QuickAdapter#QuickAdapter(Context,int) but with
         * some initialization data.
         *
         * @param data A new list is created out of this one to avoid mutable list
         */
        public MultiItemAdapter(List<MultiItem> data) {
            super(data);
            addItemType(_Type_Info, R.layout.member_basic_info_layout);
            addItemType(_Type_AddressList, R.layout.member_basic_info_address_list);
            addItemType(_Type_AddAddress, R.layout.member_basic_info_add_address);

        }

        @Override
        protected void convert(BaseViewHolder viewHolder, MultiItem item) {
            switch (item.getItemType()) {
                case _Type_AddAddress:
                    createAddressBtn = viewHolder.getView(R.id.create_address_btn);
                    createAddressBtn.setOnClickListener(v -> {
                        Intent intent = new Intent(mContext, CreateNewAddressActivity.class);
                        intent.putExtra("memberName", mMemberName);
                        intent.putExtra("phone", mPhone);
                        intent.putExtra("memberID", mMemberID);
                        startActivityForResult(intent, _SAVE_MEMBER_ADDRESS_REQUEST_CODE);
                        overridePendingTransition(R.anim.page_in_left, R.anim.page_out_right);
                    });
                    break;
                case _Type_AddressList:
                    addressRecycler = viewHolder.getView(R.id.address_recycler);
                    addressRecycler.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
                    addressRecycler.setAdapter(mAddressAdapter);
                    mAddressAdapter.emptyView = getLayoutInflater().inflate(R.layout.address_list_empty_layout, (ViewGroup) addressRecycler.getParent(), false);
                    mAddressAdapter.setEmptyView(mAddressAdapter.emptyView);
                    break;
                case _Type_Info:
                    nameTv = viewHolder.getView(R.id.name_tv);
                    mobileTv = viewHolder.getView(R.id.mobile_tv);
                    avatarIv = viewHolder.getView(R.id.avatar_iv);
                    tagLayout = viewHolder.getView(R.id.tag_layout);
                    nameEdt = viewHolder.getView(R.id.name_edt);
                    weiboEdt = viewHolder.getView(R.id.weibo_edt);
                    remarkEdt = viewHolder.getView(R.id.remark_edt);
                    tencentEdt = viewHolder.getView(R.id.tencent_edt);
                    wechatEdt = viewHolder.getView(R.id.wechat_edt);
                    mobileEdt = viewHolder.getView(R.id.mobile_edt);
                    birthDayTv = viewHolder.getView(R.id.birthday_tv);
                    childBirthdayTv = viewHolder.getView(R.id.child_birthday_tv);
                    consumptionLayout = viewHolder.getView(R.id.consumption_layout);

                    nameTv.setText(mMemberName);
                    nameEdt.setText(mMemberName);
                    mobileTv.setText(mPhone);

                    tagLayout.setOnClickListener(v -> {
                        Intent intent = new Intent(mContext, MemberTagInfoActivity.class);
                        intent.putExtra("id",mMemberID);
                        startActivity(intent);
                    });
                    consumptionLayout.setOnClickListener(v -> {
                        Intent intent = new Intent(mContext, ConsumptionActivity.class);
                        intent.putExtra("phone",mPhone);
                        startActivity(intent);
                    });
                    break;
            }
        }

    }
}
